package com.cgsd.heyu.ui.info;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.adapter.ClickItemListener;
import com.android.library.adapter.ClickTypeListener;
import com.android.library.utils.FileUtils;
import com.android.library.utils.StringUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.adapter.FeedbackImageAdapter;
import com.cgsd.heyu.common.AppMobclickAgent;
import com.cgsd.heyu.entity.TabEntity;
import com.cgsd.heyu.presenter.user.UserContract;
import com.cgsd.heyu.presenter.user.UserPresenter;
import com.cgsd.heyu.ui.BaseActivity;
import com.cgsd.heyu.utils.UploadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoxing
 * Description 意见反馈
 * CreateData: 2020/11/13
 */
public class FeedBackActivity extends BaseActivity<UserContract.Presenter> implements TextWatcher, ClickTypeListener, ClickItemListener, UserContract.FeedBackView, View.OnClickListener {
    /**
     * 反馈内容最大个数
     */
    private final int MAX_SIZE = 500;
    /**
     * 最大图片数
     */
    public static final int MAX_ITEM = 3;
    private TextView tvNum;
    private EditText edtContent;
    private FeedbackImageAdapter adapter;
    private List<TabEntity> data = new ArrayList<>();
    private int currentPosition;
    /**
     * 判断是否是更新图片
     */
    private boolean isUpdate;
    private int uploadSuccessNum;
    private List<String> uploadImages;

    public static void actionStart(Activity activity){
        AppMobclickAgent.onEvent(AppMobclickAgent.YIJIANFANKUIYE);
        Intent intent = new Intent(activity,FeedBackActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initView() {
        new UserPresenter(this);
        tvNum = findViewById(R.id.tv_num);
        edtContent = findViewById(R.id.edt_content);
        RecyclerView mRecyclerView = findViewById(R.id.mRecyclerView);

        mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
        data.add(new TabEntity());
        adapter = new FeedbackImageAdapter(this,data);
        mRecyclerView.setAdapter(adapter);
        adapter.setClickTypeListener(this);
        adapter.setClickItemListener(this);

        edtContent.addTextChangedListener(this);

        findViewById(R.id.tv_submit).setOnClickListener(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        edtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_SIZE)});
        tvNum.setText(0+"/"+MAX_SIZE);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void afterTextChanged(Editable s) {
        tvNum.setText(s.length()+"/"+MAX_SIZE);
    }

    @Override
    public void clickTypePosition(View view, int type, int position) {
        removeData(position);
    }

    @Override
    public void clickItem(View view, int position) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //添加还未授予的权限
           showToast("未获取到读写文件权限，请开启文件权限");
           return;
        }
        currentPosition = position;
        launcher.launch("image/*");
        if (!isDefaultImage(position)){
            isUpdate = true;
        }else {
            isUpdate = false;
        }

    }

    /**
     * 启动系统相册后返回的路劲
     */
    private ActivityResultLauncher<String> launcher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
           String path = FileUtils.getUriPath(FeedBackActivity.this,uri);
           if (path == null){
               return;
           }
           if (isUpdate){
               update(path);
           }else {
               addData(path);
           }
        }
    });


    /**
     * 添加数据
     */
    private void addData(String path){
        TabEntity tabEntity = new TabEntity();
        tabEntity.imgUrl = path;
        data.add(data.size()-1,tabEntity);
        adapter.notifyDataSetChanged();
        if (data.size() > MAX_ITEM){
            data.remove(data.size() -1);
            adapter.notifyItemRemoved(data.size() - 1);
        }
    }

    /**
     * 更新数据
     */
    private void update(String path){
        TabEntity tabEntity = data.get(currentPosition);
        tabEntity.imgUrl = path;
        adapter.notifyItemChanged(currentPosition);
    }

    /**
     * 删除
     * @param position
     */
    private void removeData(int position){
        data.remove(position);
        adapter.notifyItemRemoved(position);
        adapter.notifyItemRangeChanged(position,data.size() - position);
        if (!isDefaultImage(data.size() - 1)){
            data.add(new TabEntity());
            adapter.notifyItemInserted(data.size() - 1);
            adapter.notifyItemRangeChanged(data.size() - 1,data.size() - data.size() - 1);
        }
    }

    /**
     * 判断点击的是否是默认图
     */
    private boolean isDefaultImage(int position){
        if (position < data.size() - 1){
            return false;
        }
        if (StringUtils.isEmpty(data.get(position).imgUrl)){
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_submit:
                submitData();
                break;
            default:
        }
    }

    /**
     * 提交反馈数据
     */
    public void submitData(){
        if(TextUtils.isEmpty(edtContent.getText())){
            showToast(getString(R.string.input_empty));
            return;
        }
        showCommonSubmitDialog("");
        int size = isDefaultImage(data.size() - 1) ? data.size() - 1: data.size();
        List<String> keys = UploadUtils.createImageNameList(size);
        uploadImages = UploadUtils.getUploadImages(keys);
        List<String> paths = new ArrayList<>(size);
        for (TabEntity entity : data){
            if (entity.imgUrl != null){
                paths.add(entity.imgUrl);
            }
        }
        uploadSuccessNum = 0;
        if (paths.size() > 0){
            mPresenter.uploadImage(paths,keys);
        }else {
            mPresenter.feedBack(uploadImages,edtContent.getText().toString());
        }

    }

    @Override
    public void uploadImageSuccess(String key) {
        uploadSuccessNum++;
        if (uploadSuccessNum == uploadImages.size()){
            //图片全部上传完成
            mPresenter.feedBack(uploadImages,edtContent.getText().toString());
        }
    }

    @Override
    public void feedBackSuccess() {
        dismissCommonSubmitDialog();
        showToast(getString(R.string.submit_success));
        finish();
    }
}
